home *** CD-ROM | disk | FTP | other *** search
/ EuroCD 3 / EuroCD 3.iso / Programming / Python1.4_Source / Python / pythonrun.c < prev    next >
C/C++ Source or Header  |  1998-06-24  |  15KB  |  760 lines

  1. /***********************************************************
  2. Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
  3. The Netherlands.
  4.  
  5.                         All Rights Reserved
  6.  
  7. Permission to use, copy, modify, and distribute this software and its
  8. documentation for any purpose and without fee is hereby granted,
  9. provided that the above copyright notice appear in all copies and that
  10. both that copyright notice and this permission notice appear in
  11. supporting documentation, and that the names of Stichting Mathematisch
  12. Centrum or CWI or Corporation for National Research Initiatives or
  13. CNRI not be used in advertising or publicity pertaining to
  14. distribution of the software without specific, written prior
  15. permission.
  16.  
  17. While CWI is the initial source for this software, a modified version
  18. is made available by the Corporation for National Research Initiatives
  19. (CNRI) at the Internet address ftp://ftp.python.org.
  20.  
  21. STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
  22. REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
  23. MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
  24. CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
  25. DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
  26. PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  27. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  28. PERFORMANCE OF THIS SOFTWARE.
  29.  
  30. ******************************************************************/
  31.  
  32. /* Python interpreter top-level routines, including init/exit */
  33.  
  34. #include "allobjects.h"
  35.  
  36. #include "grammar.h"
  37. #include "node.h"
  38. #include "parsetok.h"
  39. #include "graminit.h"
  40. #undef argument /* Avoid conflict on Mac */
  41. #include "errcode.h"
  42. #include "sysmodule.h"
  43. #include "bltinmodule.h"
  44. #include "compile.h"
  45. #include "eval.h"
  46. #include "ceval.h"
  47. #include "import.h"
  48. #include "marshal.h"
  49.  
  50. #ifdef HAVE_SIGNAL_H
  51. #include <signal.h>
  52. #endif
  53.  
  54. #ifdef MS_WIN32
  55. #undef BYTE
  56. #undef arglist
  57. #include "windows.h"
  58. #endif
  59.  
  60. extern char *getpythonpath Py_PROTO((void));
  61.  
  62. extern grammar gram; /* From graminit.c */
  63.  
  64. /* Forward */
  65. static void initmain PROTO((void));
  66. static object *run_err_node PROTO((node *n, char *filename,
  67.                    object *globals, object *locals));
  68. static object *run_node PROTO((node *n, char *filename,
  69.                    object *globals, object *locals));
  70. static object *run_pyc_file PROTO((FILE *fp, char *filename,
  71.                    object *globals, object *locals));
  72. static void err_input PROTO((perrdetail *));
  73. static void initsigs PROTO((void));
  74.  
  75. int debugging; /* Needed by parser.c */
  76. int verbose; /* Needed by import.c */
  77. int suppress_print; /* Needed by ceval.c */
  78.  
  79. /* Initialize all */
  80.  
  81. void
  82. initall()
  83. {
  84.     static int inited;
  85.     
  86.     if (inited)
  87.         return;
  88.     inited = 1;
  89.     
  90.     initimport();
  91.     
  92.     /* Modules '__builtin__' and 'sys' are initialized here,
  93.        they are needed by random bits of the interpreter.
  94.        All other modules are optional and are initialized
  95.        when they are first imported. */
  96.     
  97.     initbuiltin(); /* Also initializes builtin exceptions */
  98.     initsys();
  99.  
  100.     setpythonpath(getpythonpath());
  101.  
  102.     initsigs(); /* Signal handling stuff, including initintr() */
  103.  
  104.     initmain();
  105. }
  106.  
  107. /* Create __main__ module */
  108.  
  109. static void
  110. initmain()
  111. {
  112.     object *m, *d;
  113.     m = add_module("__main__");
  114.     if (m == NULL)
  115.         fatal("can't create __main__ module");
  116.     d = getmoduledict(m);
  117.     if (dictlookup(d, "__builtins__") == NULL) {
  118.         if (dictinsert(d, "__builtins__", getbuiltins()))
  119.             fatal("can't add __builtins__ to __main__");
  120.     }
  121. }
  122.  
  123. /* Parse input from a file and execute it */
  124.  
  125. int
  126. run(fp, filename)
  127.     FILE *fp;
  128.     char *filename;
  129. {
  130.     if (filename == NULL)
  131.         filename = "???";
  132.     if (isatty((int)fileno(fp)))
  133.         return run_tty_loop(fp, filename);
  134.     else
  135.         return run_script(fp, filename);
  136. }
  137.  
  138. int
  139. run_tty_loop(fp, filename)
  140.     FILE *fp;
  141.     char *filename;
  142. {
  143.     object *v;
  144.     int ret;
  145.     v = sysget("ps1");
  146.     if (v == NULL) {
  147.         sysset("ps1", v = newstringobject(">>> "));
  148.         XDECREF(v);
  149.     }
  150.     v = sysget("ps2");
  151.     if (v == NULL) {
  152.         sysset("ps2", v = newstringobject("... "));
  153.         XDECREF(v);
  154.     }
  155.     for (;;) {
  156.         ret = run_tty_1(fp, filename);
  157. #ifdef Py_REF_DEBUG
  158.         fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
  159. #endif
  160.         if (ret == E_EOF)
  161.             return 0;
  162.         /*
  163.         if (ret == E_NOMEM)
  164.             return -1;
  165.         */
  166.     }
  167. }
  168.  
  169. int
  170. run_tty_1(fp, filename)
  171.     FILE *fp;
  172.     char *filename;
  173. {
  174.     object *m, *d, *v, *w;
  175.     node *n;
  176.     perrdetail err;
  177.     char *ps1, *ps2;
  178.     v = sysget("ps1");
  179.     w = sysget("ps2");
  180.     if (v != NULL && is_stringobject(v)) {
  181.         INCREF(v);
  182.         ps1 = getstringvalue(v);
  183.     }
  184.     else {
  185.         v = NULL;
  186.         ps1 = "";
  187.     }
  188.     if (w != NULL && is_stringobject(w)) {
  189.         INCREF(w);
  190.         ps2 = getstringvalue(w);
  191.     }
  192.     else {
  193.         w = NULL;
  194.         ps2 = "";
  195.     }
  196.     BGN_SAVE
  197.     n = parsefile(fp, filename, &gram, single_input, ps1, ps2, &err);
  198.     END_SAVE
  199.     XDECREF(v);
  200.     XDECREF(w);
  201.     if (n == NULL) {
  202.         if (err.error == E_EOF) {
  203.             if (err.text)
  204.                 free(err.text);
  205.             return E_EOF;
  206.         }
  207.         err_input(&err);
  208.         print_error();
  209.         return err.error;
  210.     }
  211.     m = add_module("__main__");
  212.     if (m == NULL)
  213.         return -1;
  214.     d = getmoduledict(m);
  215.     v = run_node(n, filename, d, d);
  216.     if (v == NULL) {
  217.         print_error();
  218.         return -1;
  219.     }
  220.     DECREF(v);
  221.     flushline();
  222.     return 0;
  223. }
  224.  
  225. int
  226. run_script(fp, filename)
  227.     FILE *fp;
  228.     char *filename;
  229. {
  230.     object *m, *d, *v;
  231.     char *ext;
  232.  
  233.     m = add_module("__main__");
  234.     if (m == NULL)
  235.         return -1;
  236.     d = getmoduledict(m);
  237.     ext = filename + strlen(filename) - 4;
  238. #ifdef macintosh
  239.     /* On a mac, we also assume a pyc file for types 'PYC ' and 'APPL' */
  240.     if ( strcmp(ext, ".pyc") == 0 || getfiletype(filename) == 'PYC ' ||
  241.                     getfiletype(filename) == 'APPL' ) {
  242. #else
  243. #ifdef _AMIGA
  244.     /* On amiga, files are case insensitive */
  245.     if ( stricmp(ext, ".pyc") == 0 ) {
  246. #else
  247.     if ( strcmp(ext, ".pyc") == 0 ) {
  248. #endif /* _AMIGA */
  249. #endif /* macintosh */
  250.         /* Try to run a pyc file. First, re-open in binary */
  251.         /* Don't close, done in main: fclose(fp); */
  252.         if( (fp = fopen(filename, "rb")) == NULL ) {
  253.             fprintf(stderr, "python: Can't reopen .pyc file\n");
  254.             return -1;
  255.         }
  256.         v = run_pyc_file(fp, filename, d, d);
  257.     } else {
  258.         v = run_file(fp, filename, file_input, d, d);
  259.     }
  260.     if (v == NULL) {
  261.         print_error();
  262.         return -1;
  263.     }
  264.     DECREF(v);
  265.     flushline();
  266.     return 0;
  267. }
  268.  
  269. int
  270. run_command(command)
  271.     char *command;
  272. {
  273.     object *m, *d, *v;
  274.     m = add_module("__main__");
  275.     if (m == NULL)
  276.         return -1;
  277.     d = getmoduledict(m);
  278.     v = run_string(command, file_input, d, d);
  279.     if (v == NULL) {
  280.         print_error();
  281.         return -1;
  282.     }
  283.     DECREF(v);
  284.     flushline();
  285.     return 0;
  286. }
  287.  
  288. void
  289. print_error()
  290. {
  291.     object *exception, *v, *tb, *f;
  292.     err_fetch(&exception, &v, &tb);
  293.     flushline();
  294.     fflush(stdout);
  295.     if (exception == NULL)
  296.         fatal("print_error called but no exception");
  297.     if (exception == SystemExit) {
  298.         if (v == NULL || v == None)
  299.             goaway(0);
  300.         if (is_intobject(v))
  301.             goaway((int)getintvalue(v));
  302.         else {
  303.             /* OK to use real stderr here */
  304.             printobject(v, stderr, PRINT_RAW);
  305.             fprintf(stderr, "\n");
  306.             goaway(1);
  307.         }
  308.     }
  309.     sysset("last_type", exception);
  310.     sysset("last_value", v);
  311.     sysset("last_traceback", tb);
  312.     f = sysget("stderr");
  313.     if (f == NULL)
  314.         fprintf(stderr, "lost sys.stderr\n");
  315.     else {
  316.         tb_print(tb, f);
  317.         if (exception == SyntaxError) {
  318.             object *message;
  319.             char *filename, *text;
  320.             int lineno, offset;
  321.             if (!getargs(v, "(O(ziiz))", &message,
  322.                      &filename, &lineno, &offset, &text))
  323.                 err_clear();
  324.             else {
  325.                 char buf[10];
  326.                 writestring("  File \"", f);
  327.                 if (filename == NULL)
  328.                     writestring("<string>", f);
  329.                 else
  330.                     writestring(filename, f);
  331.                 writestring("\", line ", f);
  332.                 sprintf(buf, "%d", lineno);
  333.                 writestring(buf, f);
  334.                 writestring("\n", f);
  335.                 if (text != NULL) {
  336.                     char *nl;
  337.                     if (offset > 0 &&
  338.                         offset == strlen(text))
  339.                         offset--;
  340.                     for (;;) {
  341.                         nl = strchr(text, '\n');
  342.                         if (nl == NULL ||
  343.                             nl-text >= offset)
  344.                             break;
  345.                         offset -= (nl+1-text);
  346.                         text = nl+1;
  347.                     }
  348.                     while (*text == ' ' || *text == '\t') {
  349.                         text++;
  350.                         offset--;
  351.                     }
  352.                     writestring("    ", f);
  353.                     writestring(text, f);
  354.                     if (*text == '\0' ||
  355.                         text[strlen(text)-1] != '\n')
  356.                         writestring("\n", f);
  357.                     writestring("    ", f);
  358.                     offset--;
  359.                     while (offset > 0) {
  360.                         writestring(" ", f);
  361.                         offset--;
  362.                     }
  363.                     writestring("^\n", f);
  364.                 }
  365.                 INCREF(message);
  366.                 DECREF(v);
  367.                 v = message;
  368.             }
  369.         }
  370.         if (is_classobject(exception)) {
  371.             object* className = ((classobject*)exception)->cl_name;
  372.             if (className == NULL)
  373.                 writestring("<unknown>", f);
  374.             else {
  375.                 if (writeobject(className, f, PRINT_RAW) != 0)
  376.                     err_clear();
  377.             }
  378.         } else {
  379.             if (writeobject(exception, f, PRINT_RAW) != 0)
  380.                 err_clear();
  381.         }
  382.         if (v != NULL && v != None) {
  383.             writestring(": ", f);
  384.             if (writeobject(v, f, PRINT_RAW) != 0)
  385.                 err_clear();
  386.         }
  387.         writestring("\n", f);
  388.     }
  389.     XDECREF(exception);
  390.     XDECREF(v);
  391.     XDECREF(tb);
  392. }
  393.  
  394. object *
  395. run_string(str, start, globals, locals)
  396.     char *str;
  397.     int start;
  398.     object *globals, *locals;
  399. {
  400.     return run_err_node(parse_string(str, start),
  401.                 "<string>", globals, locals);
  402. }
  403.  
  404. object *
  405. run_file(fp, filename, start, globals, locals)
  406.     FILE *fp;
  407.     char *filename;
  408.     int start;
  409.     object *globals, *locals;
  410. {
  411.     return run_err_node(parse_file(fp, filename, start),
  412.                 filename, globals, locals);
  413. }
  414.  
  415. static object *
  416. run_err_node(n, filename, globals, locals)
  417.     node *n;
  418.     char *filename;
  419.     object *globals, *locals;
  420. {
  421.     if (n == NULL)
  422.         return  NULL;
  423.     return run_node(n, filename, globals, locals);
  424. }
  425.  
  426. static object *
  427. run_node(n, filename, globals, locals)
  428.     node *n;
  429.     char *filename;
  430.     object *globals, *locals;
  431. {
  432.     codeobject *co;
  433.     object *v;
  434.     co = compile(n, filename);
  435.     freetree(n);
  436.     if (co == NULL)
  437.         return NULL;
  438.     v = eval_code(co, globals, locals);
  439.     DECREF(co);
  440.     return v;
  441. }
  442.  
  443. static object *
  444. run_pyc_file(fp, filename, globals, locals)
  445.     FILE *fp;
  446.     char *filename;
  447.     object *globals, *locals;
  448. {
  449.     codeobject *co;
  450.     object *v;
  451.     long magic;
  452.     long get_pyc_magic();
  453.  
  454.     magic = rd_long(fp);
  455.     if (magic != get_pyc_magic()) {
  456.         err_setstr(RuntimeError,
  457.                "Bad magic number in .pyc file");
  458.         return NULL;
  459.     }
  460.     (void) rd_long(fp);
  461.     v = rd_object(fp);
  462.     fclose(fp);
  463.     if (v == NULL || !is_codeobject(v)) {
  464.         XDECREF(v);
  465.         err_setstr(RuntimeError,
  466.                "Bad code object in .pyc file");
  467.         return NULL;
  468.     }
  469.     co = (codeobject *)v;
  470.     v = eval_code(co, globals, locals);
  471.     DECREF(co);
  472.     return v;
  473. }
  474.  
  475. object *
  476. compile_string(str, filename, start)
  477.     char *str;
  478.     char *filename;
  479.     int start;
  480. {
  481.     node *n;
  482.     codeobject *co;
  483.     n = parse_string(str, start);
  484.     if (n == NULL)
  485.         return NULL;
  486.     co = compile(n, filename);
  487.     freetree(n);
  488.     return (object *)co;
  489. }
  490.  
  491. /* Simplified interface to parsefile -- return node or set exception */
  492.  
  493. node *
  494. parse_file(fp, filename, start)
  495.     FILE *fp;
  496.     char *filename;
  497.     int start;
  498. {
  499.     node *n;
  500.     perrdetail err;
  501.     BGN_SAVE
  502.     n = parsefile(fp, filename, &gram, start,
  503.                 (char *)0, (char *)0, &err);
  504.     END_SAVE
  505.     if (n == NULL)
  506.         err_input(&err);
  507.     return n;
  508. }
  509.  
  510. /* Simplified interface to parsestring -- return node or set exception */
  511.  
  512. node *
  513. parse_string(str, start)
  514.     char *str;
  515.     int start;
  516. {
  517.     node *n;
  518.     perrdetail err;
  519.     n = parsestring(str, &gram, start, &err);
  520.     if (n == NULL)
  521.         err_input(&err);
  522.     return n;
  523. }
  524.  
  525. /* Set the error appropriate to the given input error code (see errcode.h) */
  526.  
  527. static void
  528. err_input(err)
  529.     perrdetail *err;
  530. {
  531.     object *v, *w;
  532.     char *msg = NULL;
  533.     v = mkvalue("(ziiz)", err->filename,
  534.                 err->lineno, err->offset, err->text);
  535.     if (err->text != NULL) {
  536.         free(err->text);
  537.         err->text = NULL;
  538.     }
  539.     switch (err->error) {
  540.     case E_SYNTAX:
  541.         msg = "invalid syntax";
  542.         break;
  543.     case E_TOKEN:
  544.         msg = "invalid token";
  545.  
  546.         break;
  547.     case E_INTR:
  548.         err_set(KeyboardInterrupt);
  549.         return;
  550.     case E_NOMEM:
  551.         err_nomem();
  552.         return;
  553.     case E_EOF:
  554.         msg = "unexpected EOF while parsing";
  555.         break;
  556.     default:
  557.         fprintf(stderr, "error=%d\n", err->error);
  558.         msg = "unknown parsing error";
  559.         break;
  560.     }
  561.     w = mkvalue("(sO)", msg, v);
  562.     XDECREF(v);
  563.     err_setval(SyntaxError, w);
  564.     XDECREF(w);
  565. }
  566.  
  567. /* Print fatal error message and abort */
  568.  
  569. void
  570. fatal(msg)
  571.     char *msg;
  572. {
  573.     fprintf(stderr, "Fatal Python error: %s\n", msg);
  574. #ifdef macintosh
  575.     for (;;);
  576. #endif
  577. #ifdef MS_WIN32
  578.     OutputDebugString("Fatal Python error:");
  579.     OutputDebugString(msg);
  580.     OutputDebugString("\n");
  581. #endif
  582.     abort();
  583. }
  584.  
  585. /* Clean up and exit */
  586.  
  587. #ifdef WITH_THREAD
  588. #include "thread.h"
  589. int threads_started = 0; /* Set by threadmodule.c and maybe others */
  590. #endif
  591.  
  592. #define NEXITFUNCS 32
  593. static void (*exitfuncs[NEXITFUNCS]) Py_PROTO((void));
  594. static int nexitfuncs = 0;
  595.  
  596. int Py_AtExit(func)
  597.     void (*func) PROTO((void));
  598. {
  599.     if (nexitfuncs >= NEXITFUNCS)
  600.         return -1;
  601.     exitfuncs[nexitfuncs++] = func;
  602.     return 0;
  603. }
  604.  
  605. void
  606. cleanup()
  607. {
  608.     object *exitfunc = sysget("exitfunc");
  609.  
  610.     if (exitfunc) {
  611.         object *res;
  612.         INCREF(exitfunc);
  613.         sysset("exitfunc", (object *)NULL);
  614.         res = call_object(exitfunc, (object *)NULL);
  615.         if (res == NULL) {
  616.             fprintf(stderr, "Error in sys.exitfunc:\n");
  617.             print_error();
  618.         }
  619.         DECREF(exitfunc);
  620.     }
  621.  
  622.     flushline();
  623.  
  624.     while (nexitfuncs > 0)
  625.         (*exitfuncs[--nexitfuncs])();
  626. }
  627.  
  628. #ifdef COUNT_ALLOCS
  629. extern void dump_counts PROTO((void));
  630. #endif
  631.  
  632. void
  633. goaway(sts)
  634.     int sts;
  635. {
  636.     cleanup();
  637.  
  638. #ifdef COUNT_ALLOCS
  639.     dump_counts();
  640. #endif
  641.  
  642. #ifdef WITH_THREAD
  643.  
  644.     /* Other threads may still be active, so skip most of the
  645.        cleanup actions usually done (these are mostly for
  646.        debugging anyway). */
  647.     
  648.     (void) save_thread();
  649. #ifndef NO_EXIT_PROG
  650.     if (threads_started)
  651.         _exit_prog(sts);
  652.     else
  653.         exit_prog(sts);
  654. #else /* !NO_EXIT_PROG */
  655.     if (threads_started)
  656.         _exit(sts);
  657.     else
  658.         exit(sts);
  659. #endif /* !NO_EXIT_PROG */
  660.     
  661. #else /* WITH_THREAD */
  662.     
  663.     doneimport();
  664.     
  665.     err_clear();
  666.  
  667. #ifdef Py_REF_DEBUG
  668.     fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
  669. #endif
  670.  
  671. #ifdef Py_TRACE_REFS
  672.     if (askyesno("Print left references?")) {
  673.         _Py_PrintReferences(stderr);
  674.     }
  675. #endif /* Py_TRACE_REFS */
  676.  
  677. #ifdef macintosh
  678.     PyMac_Exit(sts);
  679. #else
  680.     exit(sts);
  681. #endif
  682. #endif /* WITH_THREAD */
  683.     /*NOTREACHED*/
  684. }
  685.  
  686. #ifdef HAVE_SIGNAL_H
  687.  
  688. static RETSIGTYPE sighandler Py_PROTO((int));
  689.  
  690. static RETSIGTYPE
  691. sighandler(sig)
  692.     int sig;
  693. {
  694.     signal(sig, SIG_DFL); /* Don't catch recursive signals */
  695.     cleanup(); /* Do essential clean-up */
  696. #if defined(HAVE_GETPID) && defined(HAVE_KILL)
  697.     kill(getpid(), sig); /* Pretend the signal killed us */
  698. #else
  699.     exit(1);
  700. #endif
  701.     /*NOTREACHED*/
  702. }
  703. #endif
  704.  
  705. static void
  706. initsigs()
  707. {
  708.     RETSIGTYPE (*t)();
  709. #ifdef HAVE_SIGNAL_H
  710. #ifdef SIGPIPE
  711.     signal(SIGPIPE, SIG_IGN);
  712. #endif
  713. #ifdef SIGHUP
  714.     t = signal(SIGHUP, SIG_IGN);
  715.     if (t == SIG_DFL)
  716.         signal(SIGHUP, sighandler);
  717.     else
  718.         signal(SIGHUP, t);
  719. #endif              
  720. #ifdef SIGTERM
  721.     t = signal(SIGTERM, SIG_IGN);
  722.     if (t == SIG_DFL)
  723.         signal(SIGTERM, sighandler);
  724.     else
  725.         signal(SIGTERM, t);
  726. #endif
  727. #endif /* HAVE_SIGNAL_H */
  728.     initintr(); /* May imply initsignal() */
  729. }
  730.  
  731. #ifdef Py_TRACE_REFS
  732. /* Ask a yes/no question */
  733.  
  734. int
  735. askyesno(prompt)
  736.     char *prompt;
  737. {
  738.     char buf[256];
  739.     
  740.     printf("%s [ny] ", prompt);
  741.     if (fgets(buf, sizeof buf, stdin) == NULL)
  742.         return 0;
  743.     return buf[0] == 'y' || buf[0] == 'Y';
  744. }
  745. #endif
  746.  
  747. #ifdef MPW
  748.  
  749. /* Check for file descriptor connected to interactive device.
  750.    Pretend that stdin is always interactive, other files never. */
  751.  
  752. int
  753. isatty(fd)
  754.     int fd;
  755. {
  756.     return fd == fileno(stdin);
  757. }
  758.  
  759. #endif
  760.